<template>
    <div>
        <span class="title">用户管理</span>
        <p class="btn_group">
            <Button type="info" @click="adduser">新增用户</Button>
            <Button type="success" @click="resetuserinfo" :disabled='resetdisabled'>修改信息</Button>
            <Button type="warning" @click="resetpwd" :disabled='modifypwddisabled'>修改密码</Button>
        </p>
        <Table :data="userdata" ref="selection" :columns="userhead" stripe style="margin-top:15px;" @on-select = "selectedItem" @on-selection-change="selectedItemchange"></Table>
        <div style="margin: 10px;overflow: hidden">
            <div style="float: right;">
                <Page :total="total" :current="currenPage" @on-change="changePage" show-elevator></Page>
            </div>
        </div>

        <Modal
            :title="Title"
            v-model="useraction"
            :loading = "loading"
            @on-ok="confirmadduser"
            :mask-closable="false">
            <Form ref='form' :label-width="80">
                <FormItem label="账号名">
                    <Input v-model="account" type="text" placeholder="输入账号名"></Input>
                </FormItem>
                <FormItem label="密码">
                    <Input v-model="password" type="password" placeholder="输入密码"></Input>
                </FormItem>
                <FormItem label="确认密码">
                    <Input v-model="repassword" type="password" placeholder="确认密码"></Input>
                </FormItem>
                <FormItem label="姓名">
                    <Input v-model="username" type="text" placeholder="输入姓名"></Input>
                </FormItem>
                <FormItem label="联系电话">
                    <Input v-model="phone" placeholder="输入电话号码"></Input>
                </FormItem>
                <FormItem label="邮箱">
                    <Input v-model="email" type="email" placeholder="输入邮箱"></Input>
                </FormItem>
                <CheckboxGroup v-model="role" style="margin-left:80px;">
                    <Checkbox label="管理员"></Checkbox>
                    <Checkbox label="超级管理员"></Checkbox>
                </CheckboxGroup>
            </Form>
        </Modal>

        <Modal
            :title="resetinfotitle"
            v-model="resetinfo"
            :loading = "resetloading"
            @on-ok="confirmReset"
            :mask-closable="false">
            <Form ref='form' :label-width="80">
                <FormItem label="账号名">
                    <Input v-model="resetaccount" type="text" placeholder="输入账号名" disabled></Input>
                </FormItem>
                <FormItem label="姓名">
                    <Input v-model="resetusername" type="text" placeholder="输入姓名"></Input>
                </FormItem>
                <FormItem label="联系电话">
                    <Input v-model="resetphone" placeholder="输入电话号码"></Input>
                </FormItem>
                <FormItem label="邮箱">
                    <Input v-model="resetemail" type="email" placeholder="输入邮箱"></Input>
                </FormItem>
                <CheckboxGroup v-model="resetrole" style="margin-left:80px;">
                    <Checkbox label="管理员"></Checkbox>
                    <Checkbox label="超级管理员"></Checkbox>
                </CheckboxGroup>
            </Form>
        </Modal>

        <Modal
            :title="modifypwdtitle"
            v-model="modifypwd"
            :loading = "modifypwdloading"
            @on-ok="confirmmodifypwd"
            :mask-closable="false">
            <Form ref='form' :label-width="80">
                <FormItem label="账号名">
                    <Input v-model="modifypwdaccount" type="text" placeholder="输入账号名" disabled></Input>
                </FormItem>
                <FormItem label="新密码">
                    <Input v-model="modifynewpwd" type="password" placeholder="输入新密码"></Input>
                </FormItem>
                <FormItem label="确认密码">
                    <Input v-model="remodifypwd" type="password" placeholder="重新输入密码"></Input>
                </FormItem>
            </Form>
        </Modal>
    </div>
</template>
<script>
import util from '../../util/util'
export default {
    data(){
        return {
            currenPage:1,
            rowselect:{},
            modifypwddisabled:true,
            resetdisabled:true,
            modifypwdtitle:'修改密码',
            modifypwd:false,
            modifypwdloading:true,
            modifypwdaccount:'',
            modifynewpwd:'',
            remodifypwd:'',
            resetinfotitle:'修改用户信息',
            resetaccount:'',
            resetusername:'',
            resetphone:'',
            resetinfo:false,
            resetemail:'',
            resetrole:['管理员'],
            resetloading:true,
            role:['管理员'],
            loading:true,
            account:'',
            password:'',
            repassword:'',
            username:'',
            phone:'',
            email:'',
            Title:'新增用户',
            useraction:false,
            userhead:[
                {
                    type: 'selection',
                    width: 60,
                    align: 'center'
                },
                {
                    title: '编号',
                    type:'index',
                    sortable:true
                },
                {
                    title: '账号名称',
                    key: 'Account',
                    sortable: true
                },{
                    title: '用户角色',
                    key: 'userrole',
                    sortable: true
                },{
                    title: '姓名',
                    key: 'username',
                    sortable: true
                },{
                    title: '联系电话',
                    key: 'concatphone',
                    sortable: true
                },{
                    title: '邮箱',
                    key: 'email',
                    sortable: true
                },{
                    title: '激活状态',
                    key: 'status',
                    sortable: true
                },{
                    title: '注册时间',
                    key: 'registertime',
                    sortable: true
                },{
                    title: '操作',
                    render:(h,params)=>{
                        let type = 'default';
                        let text = '启用';
                        type = params.row.status == '已激活'?'default':'primary';
                        text = params.row.status == '已激活'?'禁用':'启用';
                        return h('div',[
                            h('Button', {
                                props: {
                                    type: type,
                                    size: 'small'
                                },
                                style: {
                                    marginRight: '5px'
                                },
                                on: {
                                    click: () => {
                                        if(text=='启用'){
                                            this.TollgeUserDisable(params.row.id,true,params,text);
                                        }else if(text=='禁用'){
                                            this.TollgeUserDisable(params.row.id,false,params,text);
                                        }
                                       
                                    }
                                }
                            }, text),
                        ])
                    }
                }
            ],
            userdata:[],
            total:1,
            Alludata:[]
        }
    },
    created(){
        this.GetUsers(1,10);
    },
    methods:{
        TollgeUserDisable:function(id,active,params,text){
            let vm = this;
            util.ajax({
                method: 'PATCH',
                url: '/api-usr/'+id+'/',
                data:{
                    is_active:active
                }
            })
            .then(function (response) {
                if(response.status==200){
                    if(!active){
                        vm.$Message.success('禁用用户成功');
                        params.row.status = '未激活';
                        text = '启用';
                    }else{
                        vm.$Message.success('启用用户成功');
                        params.row.status = '已激活';
                        text = '启用';
                    }
                    
                }else{
                    if(!active){
                        vm.$Message.error('禁用用户失败');
                    }else{
                        vm.$Message.error('启用用户失败');
                    }
                }
            })
            .catch(function(err){
                vm.$Message.error('网络错误');
            })
        },
        GetUsers:function(page,pagesize){
            let vm = this;
            util.ajax({
                method: 'get',
                url: '/api-usr/?page='+page+'&page_size='+pagesize
            })
            .then(function (response) {
                if(response.status==200){
                    vm.total = response.data.count;
                    vm.currenPage = page;
                    vm.userdata = [];
                    for(let i = 0;i<response.data.results.length;i++){
                        let userrole  = '管理员';
                        if(response.data.results[i].is_superuser){
                            userrole = '超级管理员';
                        }
                        if(!response.data.results[i].is_superuser && !response.data.results[i].is_staff){
                            userrole = '普通用户';
                        }
                        let item = {
                            id:response.data.results[i].id,
                            Account:response.data.results[i].username,
                            userrole:userrole,
                            username:response.data.results[i].fullname,
                            concatphone:response.data.results[i].contact,
                            email:response.data.results[i].email,
                            status:response.data.results[i].is_active?'已激活':'未激活',
                            registertime:response.data.results[i].date_joined
                        }
                        vm.userdata.push(item);
                    }
                }else{
                    vm.$Message.error('获取用户列表失败');
                }
            })
            .catch(function(err){
                vm.$Message.error('网络错误');
            })
        },
        changePage:function(page){
            this.GetUsers(page,10);
        },
        changeLoading() {
            this.loading = false;
            this.$nextTick(() => {
                this.loading = true;
            });
        },
        changeresetLoading() {
            this.resetloading = false;
            this.$nextTick(() => {
                this.resetloading = true;
            });
        },
        changemodifypwdLoading(){
            this.modifypwdloading = false;
            this.$nextTick(() => {
                this.modifypwdloading = true;
            });
        },
        selectedItem:function(selection,row){
            this.rowselect = row;
        },
        selectedItemchange:function(selection){
            
            if(selection.length === 1){
                this.modifypwddisabled = false;
                this.resetdisabled = false;
            }else{
                this.modifypwddisabled = true;
                this.resetdisabled = true;
            }
        },
        adduser:function(){
            this.useraction = true;
        },
        resetuserinfo:function(){
            this.resetaccount = this.rowselect.Account;
            this.resetusername = this.rowselect.username;
            this.resetphone = this.rowselect.concatphone;
            this.resetemail = this.rowselect.email;
            if(this.rowselect.userrole.indexOf(',')!==-1){
                let rolelist = this.rowselect.userrole.split(',');
                this.resetrole = rolelist;
            }else{
                if(this.rowselect.userrole){
                    this.resetrole=[];
                    this.resetrole.push(this.rowselect.userrole);
                }
            }
            
            this.resetinfo = true;
        },
        resetpwd:function(){
            this.modifypwdaccount = this.rowselect.Account;
            this.modifypwd = true;
        },
        checkoutphone:function(phoneNumber){
            let reg=11 && /^((13|14|15|17|18)[0-9]{1}\d{8})$/;
            if(phoneNumber==''){
                return false
            }else if(!reg.test(phoneNumber)){
                return false
            }
            return true;
        },
        checkemail:function(email){
　　        let reg = new RegExp("^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$"); 
            if(email===''){
                return false;
            }else if(!reg.test(email)){
                return false
            }
            return true;
        },
        confirmadduser:function(){
            if(!this.account || !this.password || !this.repassword || !this.username ||!this.phone || !this.email){
                this.$Message.error('请输入正确用户信息');
                return this.changeLoading();
            }else{
                if(!this.checkoutphone(this.phone)){
                    this.$Message.error('请输入合法的手机号码');
                    return this.changeLoading();
                }
                if(!this.checkemail(this.email)){
                    this.$Message.error('请输入合法的邮箱');
                    return this.changeLoading();
                }
                if(this.password!==this.repassword){
                    this.$Message.error('两次输入密码不同，请检查');
                    return this.changeLoading();
                }
                this.addUserReq();
            }
        },
        addUserReq:function(){
            let vm = this;
            let is_staff = false;
            let is_superuser = false;
            if(vm.role.length==2){
                is_superuser = true;
            }
            if(vm.role.length==1 && vm.role[0]=='管理员'){
                is_staff = true;
            }
            if(vm.role.length==1 && vm.role[0]=='超级管理员'){
                is_superuser = true;
            }
            util.ajax({
                method: 'post',
                url: '/api-usr/',
                data:{
                    username:vm.account,
                    password:vm.password,
                    fullname:vm.username,
                    email:vm.email,
                    contact:vm.phone,
                    is_superuser:is_superuser,
                    is_staff:is_staff
                }
            })
            .then(function (response) {
                if(response.status==201){
                    vm.changeLoading();
                    vm.useraction=false;
                    vm.GetUsers(1,10);
                    vm.$Message.success('新增用户成功');
                    vm.$refs.selection.selectAll(false);
                }else{
                    vm.$Message.error('新增用户失败');
                    return vm.changeLoading()
                }
            })
            .catch(function(err){
                vm.$Message.error('网络错误');
                return vm.changeLoading()
            })
        },
        confirmReset:function(){
            if(!this.resetaccount || !this.resetusername || !this.resetphone || !this.resetemail || !this.resetrole){
                this.$Message.error('请输入正确用户信息');
                return this.changeresetLoading();
            }else{
                if(!this.checkoutphone(this.resetphone)){
                    this.$Message.error('请输入合法的手机号码');
                    return this.changeresetLoading();
                }
                if(!this.checkemail(this.resetemail)){
                    this.$Message.error('请输入合法的邮箱');
                    return this.changeresetLoading();
                }
                this.ResetUserReq();
            }
        },
        ResetUserReq:function(){
            let vm = this;
            let is_staff = false;
            let is_superuser = false;
            if(vm.resetrole.length==2){
                is_superuser = true;
            }
            if(vm.resetrole.length==1 && vm.resetrole[0]=='管理员'){
                is_staff = true;
            }
            if(vm.resetrole.length==1 && vm.resetrole[0]=='超级管理员'){
                is_superuser = true;
            }
            util.ajax({
                method: 'PATCH',
                url: '/api-usr/'+vm.rowselect.id+'/',
                data:{
                    username:vm.resetaccount,
                    fullname:vm.resetusername,
                    email:vm.resetemail,
                    contact:vm.resetphone,
                    is_superuser:is_superuser,
                    is_staff:is_staff
                }
            })
            .then(function (response) {
                if(response.status==200){
                    vm.changeresetLoading();
                    vm.resetinfo=false;
                    vm.currenPage = 1;
                    vm.GetUsers(1,10);
                    vm.$Message.success('修改用户信息成功');
                    vm.$refs.selection.selectAll(false);
                }else{
                    vm.$Message.error('修改用户信息失败');
                    return vm.changeresetLoading()
                }
            })
            .catch(function(err){
                vm.$Message.error('网络错误');
                return vm.changeresetLoading()
            })
        },
        confirmmodifypwd:function(){
            if(!this.modifynewpwd || !this.remodifypwd){
                this.$Message.error('请输入正确的信息');
                return this.changemodifypwdLoading();
            }else{
                if(this.modifynewpwd !== this.remodifypwd){
                    this.$Message.error('两次输入密码不一致，请检查');
                    return this.changemodifypwdLoading();
                }
                this.ModifyPwdReq();
            }
        },
        ModifyPwdReq:function(){
            let vm = this;
            util.ajax({
                method: 'PATCH',
                url: '/api-usr/'+vm.rowselect.id+'/',
                data:{
                    password:vm.modifynewpwd
                }
            })
            .then(function (response) {
                if(response.status==200){
                    vm.changemodifypwdLoading();
                    vm.modifypwd=false;
                    vm.GetUsers(1,10);
                    vm.$Message.success('修改用户密码成功');
                    vm.$refs.selection.selectAll(false);
                }else{
                    vm.$Message.error('修改用户密码失败');
                    return vm.changemodifypwdLoading()
                }
            })
            .catch(function(err){
                vm.$Message.error('网络错误');
                return vm.changemodifypwdLoading()
            })
        }
    }
}
</script>
<style scoped>
.title{
        color: #0e90d2;
        font-size: 20px;
        font-weight: 700;
    }
    .btn_group{
        float: right;
    }
</style>
